import time
import base64
import json
import urllib

say_list = ["say1", "say2"]


def application(env) -> dict:
    """

    :param env: 请求报文组成的字典
    env["request_line"] = {"method":"None", "path":"None"}
    env["request_header"] = {"Host:www.xxx.com, Connection:Keep-alive"}
    env["request_body"] = {"username":"sundy"}
    :return: 响应字典
    """
    if env["request_line"]["path"] == "/login":
        cookie = env["request_header"].get("Cookie")
        if cookie is not None and base64.b64decode(cookie) == b"sundy":
            # 已经登陆过
            return {"body": "have login"}
        else:
            if env["request_body"]["username"] == "sundy":
                # 登陆成功 设置cookies
                return {"body": "login success",
                        "Set-Cookies": base64.b64encode(b"sundy").decode(
                            "utf8")}
            else:
                return {"body": "login fail"}

    if env["request_line"]["path"] == "/say_list":
        if env["request_line"]["method"] == "GET":
            # 返回所有留言列表
            return {"body": json.dumps(say_list)}

        if env["request_line"]["method"] == "POST":
            cookie = env["request_header"].get("Cookie")
            if cookie is not None and base64.b64decode(cookie) == b"sundy":
                # 已登录添加留言
                # content = urllib.parse.unquote(env["request_body"]["say_content"])
                say_list.append(env["request_body"]["say_content"])
                return {"body": "add say content success!"}
            else:
                # 未登录不可添加留言
                return {"body": "please login"}
